package com.gitee.wsl.net.client.validator


import com.gitee.wsl.transform.validator.ValidatorsRegistry
import com.gitee.wsl.transform.validator.ValidatorsRegistryScope
import io.ktor.client.plugins.api.*
import io.ktor.client.statement.*

/**
 * A plugin that validates deserialized response bodies.
 *
 * ```
 * val client = HttpClient(CIO) {
 *     install(Validator) {
 *         registerValidator(validateBook)
 *     }
 *     install(ContentNegotiation) {
 *         json()
 *     }
 * }
 * ```
 */
val Validator: ClientPlugin<ValidatorsRegistryScope> = createClientPlugin(
    name = "Validator",
    createConfiguration = { ValidatorsRegistry() }
) {
    on(ResponseBodyTransformed) { content ->
        val (_, data) = content as? HttpResponseContainer ?: return@on
        (pluginConfig as ValidatorsRegistry).validateWithResult(data).getOrThrow()
    }
}
